package cn.sjx.auth.interceptor;

import cn.sjx.auth.annotation.Permission;
import cn.sjx.auth.mapper.PermissionMapper;
import cn.sjx.basic.utils.BasicMap;
import cn.sjx.org.domain.Employee;
import cn.sjx.org.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头中的token
        String token = request.getHeader("token");
        //2. 判断token是否为空
        if (StringUtils.isEmpty(token)) {
            //2.1 如果为空拦截
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }
        //2.2 如果不为空，则通过该token从全局map中获取用户对象
        Object user = BasicMap.loginMap.get(token);
        //3. 判断用户对象是否为空
        if (Objects.isNull(user)) {
            //3.1 如果为空拦截
            response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }


        /*
         *  权限鉴定
         *  权限sn：类名:方法名
         *  handler：cn.sjx.org.controller.DepartmentController#pageList(DepartmentQuery)
         *  Object类型的handler转成HandlerMethod 再调用.getMethod() 得到Method
         */
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //1. 判断Method上是否有权限注解
        //1.1 如果没有，放行
        Permission annotation = method.getAnnotation(Permission.class);
        if (Objects.isNull(annotation)){
            return true;
        }
        //2. 通过Employee对象中的id 联合Employee_role和role_permission两张表 查询该用户下所有的权限sn
        Employee employee = (Employee)user;
        List<String> permissions =  permissionMapper.getPermissionSnsByEmployeeId(employee.getId());
        //3. 通过Method组合当前资源的权限sn
        String sn = method.getDeclaringClass().getSimpleName()+":"+method.getName();


        //4. 判断该用户下所有的权限sn中是否有当前资源的权限sn
        // 4.1 如果没有，拦截
        if (!permissions.contains(sn)) {
            response.getWriter().write("{\"success\":false,\"message\":\"noPermission\"}");
            return false;
        }

        return true;
    }
}
